package top.huhuiyu.teachproject.aop;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.huhuiyu.teachproject.anno.BucketLimit;
import top.huhuiyu.teachproject.exception.AppException;
import top.huhuiyu.teachproject.service.LimitService;

@Aspect
@Component
@Slf4j
@Order(21)
@RequiredArgsConstructor
public class ControllerBucketLimit implements BaseControllerAop {
  private final LimitService limitService;

  @Before("controller()")
  public void before(JoinPoint jp) {
    log.debug("进入===>{}", jp.getSignature());
    // 取回被切面的事件签名
    MethodSignature ms = (MethodSignature) jp.getSignature();
    // 获取方法上面的limit注解
    BucketLimit limit = ms.getMethod().getAnnotation(BucketLimit.class);
    log.debug("limit信息：{}", limit);
    // 没有限流信息
    if (limit == null) {
      return;
    }
    // 检查限流信息
    if (!limitService.checkLimit(limit)) {
      throw AppException.getInstance(limit.message());
    }

  }

}